package com.lemonfish.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lemonfish.mapper.UserMapper;
import com.lemonfish.pojo.dto.UserDTO;
import com.lemonfish.pojo.dto.UserDTOLikeSearch;
import com.lemonfish.pojo.entity.User;
import com.lemonfish.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * User相关Service实现
 *
 * @author Lemonfish
 * @version 1.0
 * @date 2020-03-01
 * Copyright © ï¿½Å³ï¿½
 */
@Service
@Slf4j
public class UserServiceImpl extends BaseCustomServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    UserMapper userMapper;

    @Override
    public IPage<User> getAllByLike(UserDTOLikeSearch content, long curPage, long pageSize, String order, String column) {
        QueryWrapper<User> queryWra = new QueryWrapper();
        System.out.println(content);
        if (!StringUtils.isEmpty(content.getName())) {
            queryWra.like("name", content.getName());
        }
        if (!StringUtils.isEmpty(content.getEmail())) {
            queryWra.like("email", content.getEmail());

        }
        if (!StringUtils.isEmpty(content.getRoleName())) {
            queryWra.eq("role_name", content.getRoleName());
        }

        if ("descending".equals(order)) {
            queryWra.orderByDesc(column);
        } else {
            queryWra.orderByAsc(column);
        }

        return userMapper.selectPage(new Page<User>(curPage, pageSize), queryWra);
    }

    @Override
    public User checkUser(UserDTO userDTO) {
        LambdaQueryWrapper<User> queryWra = new LambdaQueryWrapper<>();

        queryWra.eq(User::getUsername, userDTO.getUsername());
        queryWra.eq(User::getPassword, userDTO.getPassword());

        return userMapper.selectOne(queryWra);
    }

    @Override
    public User checkUserByName(String username) {
        LambdaQueryWrapper<User> queryWra = new LambdaQueryWrapper<>();

        queryWra.eq(User::getUsername, username);

        return userMapper.selectOne(queryWra);
    }

    @Override
    public int update(User user) {
        return userMapper.updateById(user);
    }

    @Override
    public IPage<User> getUserList(long curPage, long size, String order, String column) {
        QueryWrapper<User> queryWra = new QueryWrapper<>();

        if ("descending".equals(order)) {
            queryWra.orderByDesc(column);
        } else {
            queryWra.orderByAsc(column);
        }

        return userMapper.selectPage(new Page<User>(curPage, size), queryWra);
    }
}
